<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">



  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">




  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/avatar.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/avatar.ico?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/avatar.ico?v=6.3.0">


  <link rel="mask-icon" href="/avatar.ico?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.3.0',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="简介快速傅里叶变换(Fast Fourier Transform),简称FFTOI中主要要来加速多项式乘法">
<meta name="keywords" content="原创精华,快速傅里叶变换">
<meta property="og:type" content="article">
<meta property="og:title" content="【OI之路】11更高级数论-4快速傅里叶变换">
<meta property="og:url" content="http://zory.cf/posts/4db.html">
<meta property="og:site_name" content="Zory的个人博客">
<meta property="og:description" content="简介快速傅里叶变换(Fast Fourier Transform),简称FFTOI中主要要来加速多项式乘法">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://img.blog.csdn.net/20140401085322937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtemt5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://zory.cf/images/OI之路/快速傅里叶变换/1.png">
<meta property="og:image" content="http://img.blog.csdn.net/20140401085322937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtemt5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">
<meta property="og:image" content="http://zory.cf/images/OI之路/快速傅里叶变换/1.png">
<meta property="og:updated_time" content="2018-09-09T04:10:20.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【OI之路】11更高级数论-4快速傅里叶变换">
<meta name="twitter:description" content="简介快速傅里叶变换(Fast Fourier Transform),简称FFTOI中主要要来加速多项式乘法">
<meta name="twitter:image" content="http://img.blog.csdn.net/20140401085322937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtemt5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast">






  <link rel="canonical" href="http://zory.cf/posts/4db.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【OI之路】11更高级数论-4快速傅里叶变换 | Zory的个人博客</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?6c38ba8648d29103b8d122f998787d71";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zory的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">人生即使不能走最短路，仍是连通图</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />历程Archives<span class="badge">354</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类Categories<span class="badge">4</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签Tags<span class="badge">133</span></a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-template">
    <a href="/categories/OI之路" rel="section">
      <i class="menu-item-icon fa fa-fw fa-telegram"></i> <br />OI之路</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-problems">
    <a href="/categories/刷题" rel="section">
      <i class="menu-item-icon fa fa-fw fa-list-alt"></i> <br />刷题Problems</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-friends">
    <a href="/friends/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user-circle"></i> <br />友链Friends</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-english">
    <a href="/English/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-etsy"></i> <br />English知识体系</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-boutique">
    <a href="/tags/原创精华/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-handshake-o"></i> <br />原创精华</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-top">
    <a href="/top/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-signal"></i> <br />排行榜Hot</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />找文章强烈建议使用-搜索Search</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="这个搜索超级好用哦！找文章必备！" spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zory.cf/posts/4db.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zory">
      <meta itemprop="description" content="人生即使不能走最短路，仍是连通图">
      <meta itemprop="image" content="http://ouk2t1pgs.bkt.clouddn.com/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zory的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">【OI之路】11更高级数论-4快速傅里叶变换
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建于：2003-01-22 00:11:04" itemprop="dateCreated datePublished" datetime="2003-01-22T00:11:04+08:00">2003-01-22</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改于：2018-09-09 12:10:20" itemprop="dateModified" datetime="2018-09-09T12:10:20+08:00">2018-09-09</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/OI之路/" itemprop="url" rel="index"><span itemprop="name">OI之路</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/posts/4db.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论：</span> <span class="post-comments-count valine-comment-count" data-xid="/posts/4db.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/posts/4db.html" class="leancloud_visitors" data-flag-title="【OI之路】11更高级数论-4快速傅里叶变换">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>快速傅里叶变换(Fast Fourier Transform),简称FFT<br>OI中主要要来加速多项式乘法</p>
<a id="more"></a>
<h2 id="声明"><a href="#声明" class="headerlink" title="声明"></a>声明</h2><p>预备知识：实数，虚数<br>定义n=第一个多项式最高次+1，m=第二个多项式最高次+1<br>以$(4x^3+5)\times (x^2-6x+\sqrt3)$为例n=4，m=3</p>
<h2 id="转化"><a href="#转化" class="headerlink" title="转化"></a>转化</h2><p>对于x的多项式可以转化为对于x的函数f(x)<br>函数f(x)有两种表达方式：<strong>系数表达法</strong>和<strong>点值表达法</strong></p>
<h2 id="系数表达法"><a href="#系数表达法" class="headerlink" title="系数表达法"></a>系数表达法</h2><p>最常见的表达方式$f(x)=a_0x^0+a_1x^1+…+a_{n-1}x^{n-1}=\sum_{j=0}^{n-1}a_j x^j$</p>
<h2 id="点值表达法"><a href="#点值表达法" class="headerlink" title="点值表达法"></a>点值表达法</h2><p>原理：假设f(x)的最高次数为n−1，那么我们只要知道了n个不相同的x及f(x)值，就能确定出f(x)的多项式。<br>例如确定一个二次函数需要三个不同的点，因为有三个变量<br>那么要得到多项式乘积对应的函数，需要$(n-1)+(m-1)+1=n+m-1$个点</p>
<h2 id="函数的加法运算"><a href="#函数的加法运算" class="headerlink" title="函数的加法运算"></a>函数的加法运算</h2><p>对于系数表达法，各项系数对应相加<br>对于点值表达法，x相同的点y值相加</p>
<p>例如：<br>$A(x)=x^2+2x-1$可以被表达为$(0,-1),(1,2),(2,7)$<br>$B(x)=x^2-x+2$可以被表达为$(0,2),(1,2),(2,4)$<br>$C(x)=A(x)+B(x)=2x^2+x+1$可以被表达为$(0,1),(1,4),(2,11)$</p>
<p>两者势均力敌<br>嗯这个并不会用到，毕竟我们要解决的是多项式乘法</p>
<h2 id="函数的乘法运算"><a href="#函数的乘法运算" class="headerlink" title="函数的乘法运算"></a>函数的乘法运算</h2><p>对于系数表达法，将前面的每个项依次与后面的每个项乘机之和，时间复杂度$\Theta(n\times m)$<br>对于点值表达法，x相同的点y值相乘，时间复杂度$\Theta(n+m-1)$</p>
<p>例如：<br>$A(x)=x^2+2x-1$可以被表达为$(0,-1),(1,2),(2,7),(3,14),(4,23)$<br>$B(x)=x^2-x+2$可以被表达为$(0,2),(1,2),(2,4),(3,8),(4,14)$<br>$C(x)=A(x)\times B(x)=x^4+x^3-x^2+5x-2$<br>可以被表达为$(0,-2),(1,4),(2,28),(3,112),(4,322)$<br>可以发现A(x)和B(x)一定要取足够多（即n+m-1个）点</p>
<p>这就是快速傅里叶变换的精髓：利用点值表达法比系数表达法在乘法中更快</p>
<h2 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h2><p>引入新定义：<br><strong>求值</strong>：通过多项式的系数表示法求其点值表示法。<br><strong>插值</strong>：通过多项式的点值表示法求其系数表示法。<br>显然上面两个定义是互逆的关系。</p>
<p>方法：引用别人的一幅图，灰常清晰（如果图没了就算了）<br><img src="http://img.blog.csdn.net/20140401085322937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtemt5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt=""></p>
<h2 id="FFT"><a href="#FFT" class="headerlink" title="FFT"></a>FFT</h2><p>FFT就是用来解决求值的过程的，可以在$\Theta(nlogn)$的时间里完成DFT<br>分析一下如何得到最终的多项式吧。</p>
<ol>
<li>求A的n+m-1个单位根的点值，求B的n+m-1个单位根的点值。</li>
<li>点值相乘，得到C的点值。</li>
<li>计算C的多项式。<br>步骤2可以直接$\Theta(n+m-1)$得出，重点是步骤1和3</li>
</ol>
<h2 id="单位根"><a href="#单位根" class="headerlink" title="单位根"></a>单位根</h2><p>中途插叙这个数学上的概念，有点难，要挺过去。<br><strong>复数</strong>，就是实数+虚数，两者只能和同类型的运算，符号$i$表示是一个虚数，$i\times i=-1$<br>n次<strong>单位复数根</strong>，就是满足$\omega^n=1$的复数值$\omega$(念omega)<br>在实数范围下，满足所有n的有1，对于偶数n还有-1，然鹅在复数范围下$\omega$将更加广泛。<br>下文的n和这道题的n暂时无关。</p>
<h2 id="单位根性质-简单"><a href="#单位根性质-简单" class="headerlink" title="单位根性质-简单"></a>单位根性质-简单</h2><ul>
<li>n次单位复数根恰好有n个，标号k从0到n-1</li>
<li>预备知识$e^t=cos(t)+sin(t)i$，注意cos是实数sin是虚数</li>
<li>$\omega_n^k=e^{ \frac{k}{n}2\pi } i$，是值的定义，用于推性质</li>
<li>$\omega_n^k=cos(\frac{k}{n}2\pi)+sin(\frac{k}{n}2\pi)i$，是值的具体体现，用于代码实现</li>
<li>递推式：$ \omega_n^k=\omega_n^{k-1}\times \omega_n^1 $</li>
</ul>
<h2 id="单位根性质-复杂"><a href="#单位根性质-复杂" class="headerlink" title="单位根性质-复杂"></a>单位根性质-复杂</h2><p><strong>消去引理</strong>：$\omega_{dn}^{dk} = \omega_n^k$<br>这是利用定义得出的（因为指数是个分数，所以一样）<br>推论：$\omega_{n/2}^{n} = \omega_2^1 = -1和1中的第一个=-1$，等下会用到。</p>
<p><strong>折半引理</strong>：$(\omega_n^{k+n/2})^2=(\omega_n^k)^2 $</p>
<p>证明：<br>$$<br>\omega_n^{k+n/2} )^2<br>=\omega_n^{2k+n}<br>=\omega_n^{2k}\times \omega_n^n<br>=\omega_n^{2k}\times 1<br>=\omega_n^{2k}=(\omega_n^k)^2<br>$$<br>至于其他定理和性质，因为本文不需要就不讲了，有兴趣的自行百度就好。</p>
<h2 id="离散傅里叶变换DFT"><a href="#离散傅里叶变换DFT" class="headerlink" title="离散傅里叶变换DFT"></a>离散傅里叶变换DFT</h2><p>离散傅里叶变换(Discrete Fourier Transform)，简称DFT。<br><strong>为了方便，暂时将n设为需要带入的点数，不同于声明中的的n</strong></p>
<p>我们的目的就是从系数得到点值表示法，已知需要代入n个点<br>DFT的实质就是<strong>对一个多项式在n次单位根上求值，利用单位根的性质加速。</strong></p>
<p>$$ f(x)=\sum_{j=0}^{n-1}a_jx^j $$<br>求出x在$\omega_n^0, \omega_n^1, \omega_n^2…\omega_n^{n-1}$<br>(即n个n次单位复数根)的y值，时间复杂度$\Theta(n^2)$。<br>$$<br>DFT(k)<br>=y_k<br>=f(\omega_n^k)<br>=\sum_{j=0}^{n-1}a_j(\omega_n^k)^j<br>=\sum_{j=0}^{n-1}a_j \omega_n^{jk}<br>$$</p>
<h2 id="回到FFT-求值"><a href="#回到FFT-求值" class="headerlink" title="回到FFT-求值"></a>回到FFT-求值</h2><p>经典的分治又来了，也终于到正文了……<br>它的神奇之处在于利用了n 次单位根的一些玄学性质，<br>然后利用分治大大加速计算。</p>
<p>首先假设n是偶数，然后将偶数奇数下标分离<br>$Q(k)=a_0+a_2\times k+a_4\times k^2+…+a_n\times k^{n/2-1}$<br>$W(k)=a_1+a_3\times k+a_5\times k^2+…+a_{n-1}\times k^{n/2-1}$<br>易得$A(k)= Q(k^2)+k\times W(k^2)$</p>
<p>所以，<br>求$A(k)在k=\omega_n^0, \omega_n^1, \omega_n^2…\omega_n^{n-1}$处的值就转换成为<br>求$Q(k)和W(k)在k=(\omega_n^0)^2,(\omega_n^1)^2,(\omega_n^2)^2…(\omega_n^{n-1} )^2$处的值</p>
<p>当然这样只是相当于展开，是时候利用单位根的性质了。</p>
<p>$对于k&lt; n/2，A(\omega_n^{k})=Q((\omega_n^{k})^2)+\omega_n^k\times W((\omega_n^{k})^2)$<br>$对于k\geq n/2，A(\omega_n^{k+n/2})=Q((\omega_n^{k+n/2})^2)+\omega_n^{k+n/2}\times W((\omega_n^{k+n/2})^2)$<br>根据折半引理$(\omega_n^{k+n/2})^2=(\omega_n^k)^2$再次简化（主要是减少了带入次数）<br>$(\omega_n^{k+n/2})^2=(\omega_n^k)^2$<br>$Q(\omega_n^{k+n/2})=Q(\omega_n^k)$<br>$W(\omega_n^{k+n/2})=W(\omega_n^k)$<br>$\omega_n^{k+n/2}=\omega_n^k \times \omega_n^{n/2}=\omega_n^k \times -1=-\omega_n^k$<br>$对于k\geq n/2，A(\omega_n^{k+n/2})=Q((\omega_n^{k})^2)-\omega_n^k\times W((\omega_n^{k})^2)$</p>
<p>边界：$\omega_1^0=1$</p>
<p>对了，有木有一种熟悉感？没错，<a href="a06a.html">等比数列二分求和</a>的快速也是靠这个分治减少带入计算量！</p>
<h2 id="回到FFT-插值"><a href="#回到FFT-插值" class="headerlink" title="回到FFT-插值"></a>回到FFT-插值</h2><p>从x、y得到系数也就是插值又要怎么搞呢？<br>丢个结论（额证明我也不会）：<br>用$\omega_n^{-1}$的值代替$\omega_n^1$，根据递推式从而让所有的$\omega$都不同<br>最后再将答案除以n，得到的便是逆DFT的结果。</p>
<h2 id="再理理思路"><a href="#再理理思路" class="headerlink" title="再理理思路"></a>再理理思路</h2><p>如果n是2的幂，一路分治下去，时间复杂度$\Theta(nlogn)$……<br>如果n不是2的幂怎么办？很简单，强制取更多的点（并且是2的幂个），多项式前面的系数补0。<br>综上所述，找到比n+m-1更大或相等的2的幂作为n</p>
<p>讲一个重要的细节：$A(k)= Q(k^2)+k\times W(k^2)$这个公式在代码里的体现是将平方拆开也就是n/2传给所谓Q、W（FFT）的，所以看起来没有平方</p>
<h2 id="讲一道模版题"><a href="#讲一道模版题" class="headerlink" title="讲一道模版题"></a>讲一道模版题</h2><p>FFT基本上就讲完了，但都是理论做法，下面结合例题来看。<br><a href="http://caioj.cn/problem.php?id=1449" target="_blank" rel="noopener">Caioj1449多项式乘法</a><br>其实本文一直在解决这个问题。</p>
<h2 id="递归版代码"><a href="#递归版代码" class="headerlink" title="递归版代码"></a>递归版代码</h2><p>因为是递归，分治时n一直在变<br>首先确定：<br>当op=1也就是求值时<br>进入函数时f[i]表示将被带入的多项式的系数（n个）<br>结束函数时f[i]表示代入n次单位负数根第i个得到的值（n个）<br>当op=-1则相反</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div></pre></td><td class="code"><pre><div class="line">#include&lt;cstdio&gt;</div><div class="line">#include&lt;cstring&gt;</div><div class="line">#include&lt;algorithm&gt;</div><div class="line">#include&lt;cmath&gt;</div><div class="line">using namespace std;</div><div class="line">const int MAXN=410000;</div><div class="line">const double PI=acos(-1.0);</div><div class="line"></div><div class="line">struct cmplex</div><div class="line">&#123;</div><div class="line">    double real,imag;</div><div class="line">    cmplex() &#123;real=imag=0;&#125;</div><div class="line">    cmplex(double r,double i) &#123;real=r;imag=i;&#125;</div><div class="line">    cmplex operator + (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real+b.real,imag+b.imag);</div><div class="line">    &#125;</div><div class="line">    cmplex operator - (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real-b.real,imag-b.imag);</div><div class="line">    &#125;</div><div class="line">    cmplex operator * (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real*b.real-imag*b.imag,real*b.imag+imag*b.real);</div><div class="line">        //(a+bi)(c+di)=ac+adi+bci+bdi^2=(ac-bd)+(ad+bc)i</div><div class="line">    &#125;</div><div class="line">    //baike.baidu.com/item/复数运算法则/2568041</div><div class="line">&#125;;</div><div class="line"></div><div class="line">void FFT(cmplex *a,int op,int n)</div><div class="line">&#123;</div><div class="line">    if(n==1) return;</div><div class="line"></div><div class="line">    cmplex q[n/2],w[n/2];</div><div class="line">    for(int i=0;i&lt;=n/2-1;i++)</div><div class="line">    &#123;</div><div class="line">        q[i]=a[i*2];//偶数</div><div class="line">        w[i]=a[i*2+1];//奇数</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    FFT(q,op,n/2);FFT(w,op,n/2);//分治</div><div class="line"></div><div class="line">    cmplex wk(1,0),w1( cos(2*PI*op/n) ,sin(2*PI*op/n) );</div><div class="line">    for(int k=0;k&lt;=n/2-1;k++,wk=wk*w1)//递推式求单位根wk</div><div class="line">    &#123;</div><div class="line">        a[k]=q[k]+wk*w[k];</div><div class="line">        a[k+n/2]=q[k]-wk*w[k];</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">cmplex a[MAXN],b[MAXN],c[MAXN];</div><div class="line">int main()</div><div class="line">&#123;</div><div class="line">    int n,m;scanf("%d%d",&amp;n,&amp;m);</div><div class="line">    for(int i=0;i&lt;=n;i++) scanf("%lf",&amp;a[i].real);</div><div class="line">    for(int i=0;i&lt;=m;i++) scanf("%lf",&amp;b[i].real);</div><div class="line"></div><div class="line">    m=n+m;n=1;while(n&lt;m+1) n*=2;</div><div class="line"></div><div class="line">    FFT(a,1,n);FFT(b,1,n);//求值,n个</div><div class="line">    for(int i=0;i&lt;=n-1;i++) c[i]=a[i]*b[i];//点值表达法的乘法运算</div><div class="line">    FFT(c,-1,n);//插值,n个</div><div class="line"></div><div class="line">    for(int i=0;i&lt;=m;i++)</div><div class="line">        printf("%d ",int(c[i].real/n+0.5));</div><div class="line">        //输出系数(四舍五入后的实数部分)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="优化"><a href="#优化" class="headerlink" title="优化"></a>优化</h2><p>递归实现FFT的做法容易爆栈，而且时间较长。<br>给出两种解决方案：递归但不在函数里开数组、非递归</p>
<h2 id="递归版代码2（个人独创版）"><a href="#递归版代码2（个人独创版）" class="headerlink" title="递归版代码2（个人独创版）"></a>递归版代码2（个人独创版）</h2><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div></pre></td><td class="code"><pre><div class="line">#include&lt;cstdio&gt;</div><div class="line">#include&lt;cstring&gt;</div><div class="line">#include&lt;algorithm&gt;</div><div class="line">#include&lt;cmath&gt;</div><div class="line">using namespace std;</div><div class="line">const int MAXN=410000;</div><div class="line">const double PI=acos(-1.0);</div><div class="line"></div><div class="line">struct cmplex</div><div class="line">&#123;</div><div class="line">    double real,imag;</div><div class="line">    cmplex() &#123;real=imag=0;&#125;</div><div class="line">    cmplex(double r,double i) &#123;real=r;imag=i;&#125;</div><div class="line">    cmplex operator + (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real+b.real,imag+b.imag);</div><div class="line">    &#125;</div><div class="line">    cmplex operator - (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real-b.real,imag-b.imag);</div><div class="line">    &#125;</div><div class="line">    cmplex operator * (const cmplex &amp;b)</div><div class="line">    &#123;</div><div class="line">        return cmplex(real*b.real-imag*b.imag,real*b.imag+imag*b.real);</div><div class="line">        //(a+bi)(c+di)=ac+adi+bci+bdi^2=(ac-bd)+(ad+bc)i</div><div class="line">    &#125;</div><div class="line">    //baike.baidu.com/item/复数运算法则/2568041</div><div class="line">&#125;;</div><div class="line">cmplex t[MAXN];</div><div class="line">void FFT(cmplex *a,int op,int l,int r)</div><div class="line">&#123;</div><div class="line">    int n=(r-l+1);</div><div class="line">    if(n==1) return;//debug</div><div class="line">    int lmid=n/2;</div><div class="line">    int mid=l+lmid-1;</div><div class="line"></div><div class="line">    for(int i=l;i&lt;=r;i++) t[i]=a[i];</div><div class="line">    for(int i=0;i&lt;=lmid-1;i++)</div><div class="line">    &#123;</div><div class="line">        a[l+i]=t[l+i*2];//偶数</div><div class="line">        a[l+lmid+i]=t[l+i*2+1];//奇数</div><div class="line">    &#125;</div><div class="line">    //不复制好像也行？但代码复杂度较高</div><div class="line"></div><div class="line">    FFT(a,op,l,mid);FFT(a,op,mid+1,r);//n/2等价于平方</div><div class="line">    //for(int i=l;i&lt;=r;i++) t[i]=a[i];</div><div class="line"></div><div class="line">    cmplex wk(1,0),w1( cos(2*PI*op/n),sin(2*PI*op/n) );</div><div class="line">    for(int k=0;k&lt;=n/2-1;k++,wk=wk*w1)//递推式求单位根wk</div><div class="line">    &#123;</div><div class="line">        /*cmplex tt=wk*t[l+n/2+k];</div><div class="line">        a[l+k]=t[l+k]+tt;发现不用复制</div><div class="line">        a[l+n/2+k]=t[l+k]-tt;*/</div><div class="line">        cmplex tt=wk*a[l+n/2+k];//蝴蝶操作</div><div class="line">        a[l+n/2+k]=a[l+k]-tt;//先做这个</div><div class="line">        a[l+k]=a[l+k]+tt;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">cmplex a[MAXN],b[MAXN],c[MAXN];</div><div class="line">int main()</div><div class="line">&#123;</div><div class="line">    int n,m;scanf("%d%d",&amp;n,&amp;m);</div><div class="line">    for(int i=0;i&lt;=n;i++) scanf("%lf",&amp;a[i].real);</div><div class="line">    for(int i=0;i&lt;=m;i++) scanf("%lf",&amp;b[i].real);</div><div class="line"></div><div class="line">    m=n+m;n=1;while(n&lt;m+1) n*=2;</div><div class="line"></div><div class="line">    FFT(a,1,0,n-1);FFT(b,1,0,n-1);//求值,n个</div><div class="line">    for(int i=0;i&lt;=n-1;i++) c[i]=a[i]*b[i];//点值表达法的乘法运算</div><div class="line">    FFT(c,-1,0,n-1);//插值,n个</div><div class="line"></div><div class="line">    for(int i=0;i&lt;=m;i++)</div><div class="line">        printf("%d ",int(c[i].real/n+0.5));</div><div class="line">        //输出系数(四舍五入后的实数部分)</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="想要非递归？"><a href="#想要非递归？" class="headerlink" title="想要非递归？"></a>想要非递归？</h2><p>递归实现FFT的做法容易爆栈，而且时间较长。</p>
<p>提示：找偶数奇数分治后的结果编号规律<br><img src="../images/OI之路/快速傅里叶变换/1.png" alt=""><br>原本0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111)<br>最终0(000) 4(100) 2(010) 6(110) 1(001) 5(101) 3(011) 7(111)<br>可以发现 不断偶数奇数分离后 每个数和他二进制相反的位置互换！！<br>通俗点讲就是对于位置i，应当存放原位置是二进制翻转后的i的数值。<br>（也有的博客称其为其数值来自的位置的翻转是递增的）</p>
<p>接下来就是预处理出i对应的翻转值了，有这样一个优美的方法：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) R[i]= (R[i&gt;&gt;<span class="number">1</span>]&gt;&gt;<span class="number">1</span>) | ( (i&amp;<span class="number">1</span>)&lt;&lt;(l<span class="number">-1</span>) );</div><div class="line"><span class="comment">//位运算DP求翻转，l=logn</span></div></pre></td></tr></table></figure></p>
<p>FFT中：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) <span class="keyword">if</span>(i&lt;R[i]) swap(a[i],a[R[i]]);</div><div class="line"><span class="comment">//注意判断大小不然又换回来了</span></div></pre></td></tr></table></figure></p>
<p>其实归根结底就是把递归中调用自己的部分的前面部分即偶数奇数分离预处理出，而后再层层合并上去。</p>
<h2 id="非递归版代码"><a href="#非递归版代码" class="headerlink" title="非递归版代码"></a>非递归版代码</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//Zory-2017</span></div><div class="line"><span class="comment">//*******************头文件*******************</span></div><div class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;cstdio&gt;</span></span></div><div class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;cstring&gt;</span></span></div><div class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;cmath&gt;</span></span></div><div class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;algorithm&gt;</span></span></div><div class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</div><div class="line"><span class="comment">//*******************全局常量*******************</span></div><div class="line"><span class="keyword">const</span> <span class="keyword">double</span> PI=<span class="built_in">acos</span>(<span class="number">-1.0</span>);</div><div class="line"><span class="keyword">const</span> <span class="keyword">int</span> MAXN=<span class="number">4</span>*<span class="number">100000</span>;</div><div class="line"><span class="comment">//*******************全局定义*******************</span></div><div class="line"><span class="keyword">struct</span> <span class="keyword">complex</span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">double</span> r,i;<span class="comment">//real,imag</span></div><div class="line">    <span class="keyword">complex</span>() &#123;r=i=<span class="number">0</span>;&#125;</div><div class="line">    <span class="keyword">complex</span>(<span class="keyword">double</span> rr,<span class="keyword">double</span> ii) &#123;r=rr;i=ii;&#125;</div><div class="line">    <span class="keyword">complex</span> <span class="keyword">operator</span> + (<span class="keyword">complex</span> b) &#123;<span class="keyword">return</span> <span class="keyword">complex</span>(r+b.r,i+b.i);&#125;</div><div class="line">    <span class="keyword">complex</span> <span class="keyword">operator</span> - (<span class="keyword">complex</span> b) &#123;<span class="keyword">return</span> <span class="keyword">complex</span>(r-b.r,i-b.i);&#125;</div><div class="line">    <span class="keyword">complex</span> <span class="keyword">operator</span> * (<span class="keyword">complex</span> b) &#123;<span class="keyword">return</span> <span class="keyword">complex</span>(r*b.r-i*b.i,r*b.i+i*b.r);&#125;</div><div class="line">    <span class="comment">//(a+bi)(c+di)=ac+adi+bci+bdi^2=(ac-bd)+(ad+bc)i</span></div><div class="line">    <span class="comment">//baike.baidu.com/item/复数运算法则</span></div><div class="line">&#125;;</div><div class="line"><span class="comment">//*******************实现*******************</span></div><div class="line"><span class="keyword">int</span> R[MAXN+<span class="number">10</span>];</div><div class="line"><span class="keyword">complex</span> omega[MAXN+<span class="number">10</span>];</div><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">CalcOmega</span><span class="params">(<span class="keyword">int</span> n,<span class="keyword">int</span> op)</span></div><div class="line"></span>&#123;</div><div class="line">    <span class="keyword">double</span> t=<span class="number">2</span>*PI*op/n;</div><div class="line">    omega[<span class="number">0</span>]=<span class="keyword">complex</span>(<span class="number">1</span>,<span class="number">0</span>);</div><div class="line">    omega[<span class="number">1</span>]=<span class="keyword">complex</span>(<span class="built_in">cos</span>(t),<span class="built_in">sin</span>(t));</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> k=<span class="number">2</span>;k&lt;=n/<span class="number">2</span><span class="number">-1</span>;k++) omega[k]=omega[k<span class="number">-1</span>]*omega[<span class="number">1</span>];</div><div class="line">&#125;</div><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">FFT</span><span class="params">(<span class="keyword">complex</span> *a,<span class="keyword">int</span> n,<span class="keyword">int</span> op)</span></div><div class="line"></span>&#123;</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) <span class="keyword">if</span>(i&lt;R[i]) swap(a[i],a[R[i]]);</div><div class="line">    <span class="comment">//注意判断大小不然又换回来了</span></div><div class="line"></div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> L=<span class="number">1</span>;L&lt;=n/<span class="number">2</span>;L*=<span class="number">2</span>)<span class="comment">//合并前长度</span></div><div class="line">    &#123;</div><div class="line">        CalcOmega(L*<span class="number">2</span>,op);</div><div class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j=<span class="number">0</span>;j&lt;=n<span class="number">-1</span>;j+=L*<span class="number">2</span>)<span class="comment">//开头,长度=L*2</span></div><div class="line">        &#123;</div><div class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> k=<span class="number">0</span>;k&lt;=L<span class="number">-1</span>;k++)</div><div class="line">            &#123;</div><div class="line">                <span class="keyword">complex</span> x=a[j+k];</div><div class="line">                <span class="keyword">complex</span> y=omega[k]*a[j+L+k];</div><div class="line">                a[j+k]=x+y;</div><div class="line">                a[j+L+k]=x-y;</div><div class="line">                <span class="comment">//蝴蝶操作</span></div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">if</span>(op==<span class="number">-1</span>) <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) a[i].r=a[i].r/<span class="keyword">double</span>(n);</div><div class="line">&#125;</div><div class="line"><span class="comment">//*******************主函数*******************</span></div><div class="line"><span class="keyword">complex</span> a[MAXN+<span class="number">10</span>],b[MAXN+<span class="number">10</span>];</div><div class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></div><div class="line"></span>&#123;</div><div class="line">    <span class="keyword">int</span> n,m;<span class="built_in">scanf</span>(<span class="string">"%d%d"</span>,&amp;n,&amp;m);</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n;i++) <span class="built_in">scanf</span>(<span class="string">"%lf"</span>,&amp;a[i].r);</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=m;i++) <span class="built_in">scanf</span>(<span class="string">"%lf"</span>,&amp;b[i].r);</div><div class="line"></div><div class="line">    m=n+m+<span class="number">1</span>;<span class="keyword">int</span> <span class="built_in">log</span>=<span class="number">0</span>;n=<span class="number">1</span>;</div><div class="line">    <span class="keyword">while</span>(n&lt;m) n*=<span class="number">2</span>,<span class="built_in">log</span>++;</div><div class="line"></div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) R[i]=( R[i&gt;&gt;<span class="number">1</span>]&gt;&gt;<span class="number">1</span> ) | ( (i&amp;<span class="number">1</span>)&lt;&lt;(<span class="built_in">log</span><span class="number">-1</span>) );</div><div class="line">    <span class="comment">//nlogn翻转二进制</span></div><div class="line"></div><div class="line">    FFT(a,n,<span class="number">1</span>);FFT(b,n,<span class="number">1</span>);<span class="comment">//求值</span></div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) a[i]=a[i]*b[i];<span class="comment">//点值乘法</span></div><div class="line">    FFT(a,n,<span class="number">-1</span>);<span class="comment">//插值</span></div><div class="line"></div><div class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=m<span class="number">-1</span>;i++)</div><div class="line">        <span class="built_in">printf</span>(<span class="string">"%d "</span>,<span class="keyword">int</span>(a[i].r+<span class="number">0.5</span>));</div><div class="line">        <span class="comment">//输出系数(四舍五入后的实数部分)</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="卷积"><a href="#卷积" class="headerlink" title="卷积"></a>卷积</h2><p>最后再提提这个其实最重要的概念<br>请牢记它，很多FFT的题目都需要将公式转化为这样<br>A、B、C都是系数<br>$C_i=\sum_{k=0}^i A_k \times B_{i-k}$</p>
<h2 id="推荐好文章"><a href="#推荐好文章" class="headerlink" title="推荐好文章"></a>推荐好文章</h2><p>精品：<br><a href="http://blog.csdn.net/zxn0803/article/details/51361111" target="_blank" rel="noopener">位于CSDN-心若为城</a><br><a href="http://blog.csdn.net/iamzky/article/details/22712347" target="_blank" rel="noopener">位于CSDN-iamzky</a><br><a href="http://pan.baidu.com/s/1sliDCTZ" target="_blank" rel="noopener">位于百度云-Rose</a><br><a href="https://wenku.baidu.com/view/328f77faf18583d0486459a6.html" target="_blank" rel="noopener">位于百度文库-Voiphon</a><br><a href="http://blog.csdn.net/yangyuhao0408/article/details/60476816" target="_blank" rel="noopener">位于CSDN-oiyangyuhao</a><br><a href="https://www.cnblogs.com/Neroysq/archive/2011/10/14/2212584.html" target="_blank" rel="noopener">位于博客园-Neroysq</a><br><a href="http://blog.miskcoo.com/2015/04/polynomial-multiplication-and-fast-fourier-transform" target="_blank" rel="noopener">miskcoo</a><br><a href="http://blog.csdn.net/acdreamers/article/details/39005227" target="_blank" rel="noopener">1-位于CSDN-ACdreamers</a><br><a href="http://blog.csdn.net/acdreamers/article/details/39026505" target="_blank" rel="noopener">2-位于CSDN-ACdreamers</a></p>
<h2 id="快速复习（考前适用）"><a href="#快速复习（考前适用）" class="headerlink" title="快速复习（考前适用）"></a>快速复习（考前适用）</h2><ol>
<li><p>函数的乘法运算<br>对于系数表达法，将前面的每个项依次与后面的每个项乘机之和，时间复杂度$\Theta(n\times m)$<br>对于点值表达法，x相同的点y值相乘，时间复杂度$\Theta(n+m-1)$</p>
</li>
<li><p>求值与插值<br><img src="http://img.blog.csdn.net/20140401085322937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaWFtemt5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt=""><br>1.求A的n+m-1个单位根的点值，求B的n+m-1个单位根的点值。<br>2.点值相乘，得到C的点值。<br>3.计算C的多项式。</p>
</li>
<li><p>单位根</p>
</li>
</ol>
<ul>
<li>n次单位复数根恰好有n个，标号k从0到n-1</li>
<li>预备知识$e^t=cos(t)+sin(t)i$，注意cos是实数sin是虚数</li>
<li>$\omega_n^k=e^{ \frac{k}{n}2\pi } i$，是值的定义，用于推性质</li>
<li>$\omega_n^k=cos(\frac{k}{n}2\pi)+sin(\frac{k}{n}2\pi)i$，是值的具体体现，用于代码实现</li>
<li>递推式：$ \omega_n^k=\omega_n^{k-1}\times \omega_n^1 $</li>
<li>消去引理：$\omega_{dn}^{dk} = \omega_n^k$<br>推论：$\omega_{n/2}^{n} = \omega_2^1 = -1和1中的第一个=-1$，等下会用到。</li>
<li>折半引理：$(\omega_n^{k+n/2})^2=(\omega_n^k)^2 $</li>
</ul>
<ol>
<li>求值<br>首先假设n是偶数，然后将偶数奇数下标分离<br>$Q(k)=a_0+a_2\times k+a_4\times k^2+…+a_n\times k^{n/2-1}$<br>$W(k)=a_1+a_3\times k+a_5\times k^2+…+a_{n-1}\times k^{n/2-1}$<br>易得$A(k)= Q(k^2)+k\times W(k^2)$</li>
</ol>
<p>所以，<br>求$A(k)在k=\omega_n^0, \omega_n^1, \omega_n^2…\omega_n^{n-1}$处的值就转换成为<br>求$Q(k)和W(k)在k=(\omega_n^0)^2,(\omega_n^1)^2,(\omega_n^2)^2…(\omega_n^{n-1} )^2$处的值</p>
<p>当然这样只是相当于展开，是时候利用单位根的性质了。</p>
<p>$对于k&lt; n/2，A(\omega_n^{k})=Q((\omega_n^{k})^2)+\omega_n^k\times W((\omega_n^{k})^2)$<br>$对于k\geq n/2，A(\omega_n^{k+n/2})=Q((\omega_n^{k+n/2})^2)+\omega_n^{k+n/2}\times W((\omega_n^{k+n/2})^2)$<br>根据折半引理$(\omega_n^{k+n/2})^2=(\omega_n^k)^2$再次简化（主要是减少了带入次数）<br>$(\omega_n^{k+n/2})^2=(\omega_n^k)^2$<br>$Q(\omega_n^{k+n/2})=Q(\omega_n^k)$<br>$W(\omega_n^{k+n/2})=W(\omega_n^k)$<br>$\omega_n^{k+n/2}=\omega_n^k \times \omega_n^{n/2}=\omega_n^k \times -1=-\omega_n^k$<br>$对于k\geq n/2，A(\omega_n^{k+n/2})=Q((\omega_n^{k})^2)-\omega_n^k\times W((\omega_n^{k})^2)$</p>
<p>边界：$\omega_1^0=1$</p>
<ol>
<li><p>插值<br>用$\omega_n^{-1}$的值代替$\omega_n^1$，根据递推式从而让所有的$\omega$都不同<br>最后再将答案除以n，得到的便是逆DFT的结果。</p>
</li>
<li><p>非递归<br>找偶数奇数分治后的结果编号规律<br><img src="../images/OI之路/快速傅里叶变换/1.png" alt=""><br>原本0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111)<br>最终0(000) 4(100) 2(010) 6(110) 1(001) 5(101) 3(011) 7(111)<br>可以发现 不断偶数奇数分离后 每个数和他二进制相反的位置互换！！<br>通俗点讲就是对于位置i，应当存放原位置是二进制翻转后的i的数值。<br>（也有的博客称其为其数值来自的位置的翻转是递增的）</p>
</li>
</ol>
<p>接下来就是预处理出i对应的翻转值了，有这样一个优美的方法：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) R[i]= (R[i&gt;&gt;<span class="number">1</span>]&gt;&gt;<span class="number">1</span>) | ( (i&amp;<span class="number">1</span>)&lt;&lt;(l<span class="number">-1</span>) );</div><div class="line"><span class="comment">//位运算DP求翻转，l=logn</span></div></pre></td></tr></table></figure></p>
<p>FFT中：<br><figure class="highlight cpp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;=n<span class="number">-1</span>;i++) <span class="keyword">if</span>(i&lt;R[i]) swap(a[i],a[R[i]]);</div><div class="line"><span class="comment">//注意判断大小不然又换回来了</span></div></pre></td></tr></table></figure></p>
<p>其实归根结底就是把递归中调用自己的部分的前面部分即偶数奇数分离预处理出，而后再层层合并上去。</p>

      
    </div>

    
    
    

    
      <div class="post-tags">
        
          <a href="/tags/原创精华/" rel="tag"># 原创精华</a>
        
          <a href="/tags/快速傅里叶变换/" rel="tag"># 快速傅里叶变换</a>
        
      </div>
    

    
      

  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/c111.html" rel="bookmark">【OI之路】10字符串-1KMP</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/80c8.html" rel="bookmark">【置顶】套路集锦</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/7748.html" rel="bookmark">【OI之路】02数论算法-1公约数公倍数与欧几里得</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/f6c6.html" rel="bookmark">【OI之路】09经典问题-3哈夫曼树</a></div>
      
    </li>
  
    <li class="popular-posts-item">
      
      
      <div class="popular-posts-title"><a href="/posts/d81d.html" rel="bookmark">【OI之路】11更高级数论-3莫比乌斯反演</a></div>
      
    </li>
  
  </ul>


    

	
		<div>
				<p id="div-border-left-purple">
			   <b>本文基于<a target="_blank" title="Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)" href="http://creativecommons.org/licenses/by-sa/4.0/deed.zh"> 知识共享署名-相同方式共享 4.0 </a>国际许可协议发布</b><br/>
				<span>
				<b>本文地址：</b><a href="/posts/4db.html" title="【OI之路】11更高级数论-4快速傅里叶变换">http://zory.cf/posts/4db.html</a><br/><b>转载请注明出处，谢谢！</b>
				</span>
				</p>
		</div>
    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>哪怕是一杯奶茶，也将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Zory 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/d81d.html" rel="next" title="【OI之路】11更高级数论-3莫比乌斯反演">
                <i class="fa fa-chevron-left"></i> 【OI之路】11更高级数论-3莫比乌斯反演
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/c508.html" rel="prev" title="【OI之路】11更高级数论-5 BSGS及其拓展">
                【OI之路】11更高级数论-5 BSGS及其拓展 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://ouk2t1pgs.bkt.clouddn.com/avatar.jpg"
                alt="Zory" />
            
              <p class="site-author-name" itemprop="name">Zory</p>
              <p class="site-description motion-element" itemprop="description">人生即使不能走最短路，仍是连通图</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">354</span>
                    <span class="site-state-item-name">文章</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">133</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/Zory123" target="_blank" title="GitHub" rel="external nofollow"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1134430323@qq.com" target="_blank" title="E-Mail" rel="external nofollow"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

<script type="text/javascript" src="https://api.lwl12.com/hitokoto/main/get?encode=js&charset=utf-8"></script>
<div id="lwlhitokoto">
    <script>
        lwlhitokoto()
    </script>
</div>

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#声明"><span class="nav-text">声明</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转化"><span class="nav-text">转化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#系数表达法"><span class="nav-text">系数表达法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#点值表达法"><span class="nav-text">点值表达法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的加法运算"><span class="nav-text">函数的加法运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数的乘法运算"><span class="nav-text">函数的乘法运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#思路"><span class="nav-text">思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#FFT"><span class="nav-text">FFT</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单位根"><span class="nav-text">单位根</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单位根性质-简单"><span class="nav-text">单位根性质-简单</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#单位根性质-复杂"><span class="nav-text">单位根性质-复杂</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#离散傅里叶变换DFT"><span class="nav-text">离散傅里叶变换DFT</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#回到FFT-求值"><span class="nav-text">回到FFT-求值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#回到FFT-插值"><span class="nav-text">回到FFT-插值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#再理理思路"><span class="nav-text">再理理思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#讲一道模版题"><span class="nav-text">讲一道模版题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#递归版代码"><span class="nav-text">递归版代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化"><span class="nav-text">优化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#递归版代码2（个人独创版）"><span class="nav-text">递归版代码2（个人独创版）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#想要非递归？"><span class="nav-text">想要非递归？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#非递归版代码"><span class="nav-text">非递归版代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#卷积"><span class="nav-text">卷积</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#推荐好文章"><span class="nav-text">推荐好文章</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速复习（考前适用）"><span class="nav-text">快速复习（考前适用）</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zory</span>

  

  
</div>


  









  <div class="footer-custom">Hosted by <a target="_blank" rel="external nofollow" href="https://pages.coding.me"><b>Coding Pages</b></a></div>


        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>












  















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: true,
        appId: 'zMDFLwV3WMlWrOYhJ7tOad3M-gzGzoHsz',
        appKey: 'cJDLxDoNgzq0JJUWQFmpCRdw',
        placeholder: '对这篇文章有什么看法？大胆地说出来吧',
        avatar:'wavatar',
        guest_info:guest,
        pageSize:'20' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('2');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("zMDFLwV3WMlWrOYhJ7tOad3M-gzGzoHsz", "cJDLxDoNgzq0JJUWQFmpCRdw");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            
            counter.save(null, {
              success: function(counter) {
                
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.get('time'));
                
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            
              var newcounter = new Counter();
              /* Set ACL */
              var acl = new AV.ACL();
              acl.setPublicReadAccess(true);
              acl.setPublicWriteAccess(true);
              newcounter.setACL(acl);
              /* End Set ACL */
              newcounter.set("title", title);
              newcounter.set("url", url);
              newcounter.set("time", 1);
              newcounter.save(null, {
                success: function(newcounter) {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
                },
                error: function(newcounter, error) {
                  console.log('Failed to create');
                }
              });
            
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  

  
    
      <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      },
      TeX: {equationNumbers: { autoNumber: "AMS" }}
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/mathjax@2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

    
  


  
  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook,GooglePlus,Evernote,Vkontakte";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
  
  <script src="/lib/pangu/dist/pangu.min.js?v=3.3"></script>
  <script type="text/javascript">pangu.spacingPage();</script>


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.3.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.3.0"></script>


  

  

  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
    }

    .highlight-wrap:hover .copy-btn,
    .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  <script>
    $('.highlight').each(function (i, e) {
      var $wrap = $('<div>').addClass('highlight-wrap')
      $(e).after($wrap)
      $wrap.append($('<button>').addClass('copy-btn').append('Copy').on('click', function (e) {
        var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
          return $(e).text()
        }).toArray().join('\n')
        var ta = document.createElement('textarea')
        document.body.appendChild(ta)
        ta.style.position = 'absolute'
        ta.style.top = '0px'
        ta.style.left = '0px'
        ta.value = code
        ta.select()
        ta.focus()
        var result = document.execCommand('copy')
        document.body.removeChild(ta)
        
          if(result)$(this).text('Copied')
          else $(this).text('Copy failed')
        
        $(this).blur()
      })).on('mouseleave', function (e) {
        var $b = $(this).find('.copy-btn')
        setTimeout(function () {
          $b.text('Copy')
        }, 300)
      }).append(e)
    })
  </script>


</body>
</html>
